#!/usr/bin/env perl
use warnings;
use strict;

use DBI;
use CGI;
use Digest::SHA;

# change /path/to/includes to match your setup
BEGIN {
    use constant INCLUDES => '/path/to/includes';
    require(INCLUDES . '/functions.pl');
    require(INCLUDES . '/database.pl');
    require(INCLUDES . '/images.pl');
}

# create database connection
my $dbh = DBI->connect(DB_DBI, DB_USER, DB_PASS);

# get cookie data (login credentials)
my $cgi = CGI->new;
my $c_user = $cgi->cookie('user');

# handle the login if needed
if (defined($cgi->param('do_login'))) {
    # get login and passwd from cgi parameters
    my ($login, $passwd);
    $login = $cgi->param('login') if (defined($cgi->param('login')));
    $passwd = $cgi->param('passwd') if (defined($cgi->param('passwd')));

    if (not defined($login) or not defined($passwd)) {
        $dbh->disconnect;
        error BAD_CGI;
    }

    # generate expected identity hash
    my $sha2obj = Digest::SHA->new(512);
    $sha2obj->add($login);
    my $login_hash = $sha2obj->hex_digest();
    $sha2obj->add($passwd);
    my $passwd_hash = $sha2obj->hex_digest();
    $sha2obj->add(string_zip($login_hash, $passwd_hash));
    my $ident_hash = $sha2obj->hex_digest();

    # check database for given identity
    my $sth = $dbh->prepare("SELECT name, hash FROM users WHERE name = ? AND hash = ?");
    $sth->execute($login, $ident_hash);
    my $db_hash;
    while (my @results = $sth->fetchrow_array) {
        $c_user = $results[0];
        $db_hash = $results[1];
    }
    $sth->finish;

    if (not defined($db_hash)) {
        $dbh->disconnect;
        error BAD_CREDS;
    } else {
        print "Set-Cookie: user=$db_hash; domain=." . DOMAIN . "\n";
    }
}

# fetch user credentials
my %user = get_user($dbh, $c_user);

# no more database lookups
$dbh->disconnect;

# user's login name if logged in
my $username = (defined($user{'name'})) ? $user{'name'} : '<em>nobody</em>';

# display page content
html_begin;
html_title 'Log In';
html_body;

html_login($username);
print <<END;
        <p>Currently logged in as: $username</p>

        <form action="login.pl" method="post">
            <p>
                <input type="text" name="login" /><br />
                <input type="password" name="passwd" /><br />
                <input type="submit" name="do_login" value="Log In" />
            </p>
        </form>
END

html_end;
